﻿using DNFImagePacks2Manager.Helpers;
using System;
using System.Diagnostics;
using System.IO;

namespace DNFImagePacks2Manager.NPK
{
    public class ImageDDSIndex
    {

        public int Header { get; set; }
        public ImageType DDSType { get; set; }
        public int Index { get; set; }
        public int OriginalSize { get; set; }
        public int ImageSize { get; set; }
        public int ImageWidth { get; set; }
        public int ImageHeight { get; set; }

        public byte[] DataBytes { get; set; } = [];

        private DDSData? ddsFile = null;

        public ImageDDSIndex(BinaryReader reader)
        {
            byte[] headerBytes = reader.ReadBytes(4);
            DDSType = new(reader);
            byte[] indexBytes = reader.ReadBytes(4);
            byte[] imageSizeBytes = reader.ReadBytes(4);
            byte[] originalSizeBytes = reader.ReadBytes(4);
            byte[] imageWidthBytes = reader.ReadBytes(4);
            byte[] imageHeightBytes = reader.ReadBytes(4);

            Header = ByteHelper.Bytes2Int(headerBytes);
            Index = ByteHelper.Bytes2Int(indexBytes);
            ImageSize = ByteHelper.Bytes2Int(imageSizeBytes);
            OriginalSize = ByteHelper.Bytes2Int(originalSizeBytes);
            ImageWidth = ByteHelper.Bytes2Int(imageWidthBytes);
            ImageHeight = ByteHelper.Bytes2Int(imageHeightBytes);
        }

        public DDSData? GetDDSFile()
        {
            if (ddsFile == null && ImageSize > 0 && DataBytes.Length > 0)
            {
                byte[] bytes = DataBytes;
                try
                {
                    if (OriginalSize != DataBytes.Length && ImageSize != OriginalSize)
                    {
                        bytes = ZLibHelper.DecompressZlib(DataBytes);
                    }
                    if (bytes.Length == OriginalSize)
                    {
                        ddsFile = new DDSData(bytes);
                    }
                }
                catch (Exception) { }
            }
            return ddsFile;
        }

        public byte[] GetBytes()
        {
            return ByteHelper.IntList2Bytes([
                Header,
                DDSType.TypeCode,
                Index,
                ImageSize,
                OriginalSize,
                ImageWidth,
                ImageHeight
                ]);
        }
    }
}
